package com.lx.ngsl.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lx.ngsl.core.dto.Rap;
import com.lx.ngsl.core.dto.UserInfo;
import com.lx.ngsl.exam.autopaper.service.AutoPaperService;
import com.lx.ngsl.exam.hsitory.service.historyService;
import com.lx.ngsl.exam.quest.entity.ChoiceEntity;
import com.lx.ngsl.exam.quest.entity.QuestEntity;
import com.lx.ngsl.exam.quest.entity.WrongEntity;
import com.lx.ngsl.exam.quest.repository.WrongRepository;
import com.lx.ngsl.exam.quest.service.MistakeService;
import com.lx.ngsl.exam.quest.service.QuestService;
import com.lx.ngsl.exam.score.entity.ScoreEntity;
import com.lx.ngsl.exam.score.repository.ScoreRepository;
import com.lx.ngsl.exam.score.service.ScoreService;
import com.lx.ngsl.util.UuidUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api/exam/v0")
@Api(value="业务接口",protocols="http",tags= {"exam-app-api"})
public class ExamApi {

	@Autowired
	private MistakeService mistakeService;
	@Autowired
	private QuestService questService;
	@Autowired
	private ScoreService scoreService;
	@Autowired
	private WrongRepository wrongRepository;
	@Autowired
	historyService historyService;
	@Autowired
	private AutoPaperService autoPaperService;
	
	/*
	 * 查询错题
	 */
	@GetMapping("/mistakes")
	@ApiOperation("查询错题")
	public Map<String,Object> getMistakes(
			@ApiParam(value = "测试id", name = "testId", required = true) @RequestParam(value="testId",required=true,defaultValue="") String testId,
			@ApiParam(value = "用户id", name = "userId", required = true)@RequestParam(value="userId",required=true,defaultValue="") String userId
			){
		Map<String,Object> rs = new HashMap<>();
		//查询错题id
		List<String> ids = mistakeService.getMistakeIds(userId, testId);
		if(ids == null || ids.size() == 0) {
			rs.put("count", 0);
			rs.put("quests", new ArrayList<>());
			return rs;
		}
		//查询错题
		List<QuestEntity> quests = questService.findByIds(ids);
		
		List<Map<String,Object>> questAndChoices = new ArrayList<>();
		Map<String,Object> quest = null;
		String type = null;
		for(QuestEntity q : quests) {
			List<ChoiceEntity> choices = questService.getChoices(q.getId());
			quest = new HashMap<>();
			type = q.getType();
			quest.put("id", q.getId());
			quest.put("type", type);
			quest.put("title", q.getQuest());
			quest.put("img", q.getImg());
			if("判断题".equals(type)) {
				quest.put("choices", new ArrayList<>());
			}else {
				quest.put("choices", choices);
			}
			quest.put("answer", questService.getAnswer(q.getId(), type));
			quest.put("myanswer", mistakeService.getMyAnswer(q.getId(), userId, testId, type));
			questAndChoices.add(quest);
		}
		rs.put("count", questAndChoices.size());
		rs.put("quests", questAndChoices);
		
		return rs;
	}
	
	/*
	 * 保存测试结果
	 */
	@PostMapping("/grade")
	@ApiOperation("保存测试结果")
	@Transactional
	public Rap submitGrade(
			@ApiParam(value = "试卷id", name = "paperId", required = true)@RequestParam(value="paperId",required=true,defaultValue="") String paperId,
			@ApiParam(value = "成绩id", name = "score", required = true)@RequestParam(value="score",required=true,defaultValue="") String score,
			@ApiParam(value = "用户id", name = "userId", required = true)@RequestParam(value="userId",required=true,defaultValue="") String userId,
			@ApiParam(value = "错题", name = "wrongs", required = true)@RequestParam(value="wrongs",required=true,defaultValue="") String wrongs
			
			) {
		ScoreEntity s  = new ScoreEntity();
		s.setId(paperId);
		s.setPaperId(paperId);
		s.setScore(score);
		s.setUserId(userId);
		s.setTime(new Date());
		
		try {
			scoreService.saveScore(s);
			if(StringUtils.hasLength(wrongs)) {
				List<WrongEntity> wrongEntitys = JSON.parseObject(wrongs, new TypeReference<List<WrongEntity>>() {});
				for(WrongEntity w : wrongEntitys) {
					w.setId(UuidUtil.id());
				}
				wrongRepository.saveAll(wrongEntitys);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Rap.error(e.getMessage());
		}
		return Rap.success();
	}
	
	//历史成绩查询
	@GetMapping("/historyquery")
	@ApiOperation("历史成绩查询")
	public	List<ScoreEntity> historyquery(@ApiParam(value = "用户id", name = "userId", required = true)@RequestParam(value="userid",required=true,defaultValue = "")String userid) {
			return historyService.historyquery(userid);
		}
	
	// 试卷查询接口
	@GetMapping("/paperquery")
	@ApiOperation("历史成绩查询")
	public Map<String, Object> queryPage(@ApiParam(value = "试卷id", name = "id", required = true)@RequestParam(value = "Id", required = true, defaultValue = "") String Id) {
		 return autoPaperService.appQueryPage();
	}
}
